#pragma once
#include <iostream>
#include <functional>
#include <cstdio>
#include <string>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>

//计算任务
class CalTask
{
public:
    typedef std::function<int(int, int, char)> func_t;
    CalTask() = default;
    CalTask(int x, int y, char op, func_t func) : _x(x), _y(y), _op(op), _func(func)
    {}

    std::string operator()()
    {
        char buffer[128];
        snprintf(buffer, sizeof buffer, "%d %c %d = %d", _x, _op, _y, _func(_x, _y, _op));
        return buffer;
    }


    std::string toTastString()
    {
        char buffer[128];
        snprintf(buffer, sizeof buffer, "%d %c %d = ?", _x, _op, _y);
        return buffer;
    }


private:
    int _x;
    int _y;
    char _op;
    func_t _func;
};



const std::string operations = "+-*/%";
int MyMath(int a, int b, char op)
{
    int result;
    switch (op)
    {
    case '+':
        result = a + b;
        break;
    case '-':
        result = a - b;
        break;
    case '*':
        result = a * b;
        break;
    case '/':
    {
        if (0 == b)
        {
            std::cerr << "division zero error" << std::endl;
            result = -1;
        }
    }
    break;
    case '%':
    {
        if (0 == b)
        {
            std::cerr << "mod zero error" << std::endl;
            result = -1;
        }
    }
    break;
    default:
        // do nothing
        break;
    }

    return result;
}

class SaveTask
{
public:
    using func_t = std::function<void(const std::string&)>;
    SaveTask() = default;
    SaveTask(const std::string& message, func_t callBack) :_message(message) ,_callBack(callBack)
    {}
    void operator()()
    {
        _callBack(_message);
    }
private:
    std::string _message;
    func_t _callBack;
};

void Save(const std::string& message)
{
    std::string target = "./log.txt";
    umask(0000);
    int fd = open(target.c_str(), O_CREAT | O_WRONLY | O_APPEND, 0666);

    write(fd, message.c_str(), message.size());
    write(fd, "\n", 1);

    close(fd);
}
